const express = require("express");
const app = express();
var cookie_parser = require("cookie-parser");
const body = require("body-parser");
var dev = express.Router();
var fs = require("fs");
var multiparty = require("multiparty");
app.use("/public", express.static("public"));
app.use(body.json()); //body-parser 解析json格式数据
app.use(cookie_parser());
dev.get("/", function (req, res) {
  res.send("测试本地请求了/get");
});
dev.get("/get", function (req, res) {
  res.send("测试本地请求了/get");
});
dev.get("/list", function (req, res) {
  console.log("已有访问21");
  res.json({
    msg: "测试本地123",
    code: -1,
    ...req.cookies,
  });
});
dev.post("/add", function (req, res) {
  res.json({
    code: 0,
    msg: "测试本地请求了 /add",
    body: {
      ...req.body,
    },
  });
});
dev.post("/upla", (req, res) => {
  // 接收文件上传
  let form = new multiparty.Form({
    maxFilesSize: 500 * 1024 * 1024,
    uploadDir: "./public", //指定上传的文件路径
  });
  form.parse(req, (err, field, files) => {
    let arr =
      files &&
      files.file.map((x) => {
        // 必须这样写
        fs.rename(x.path, "./public/" + x.originalFilename, () => {
          console.log("改名");
        });
      });
    res.end(
      JSON.stringify({
        ok: 200,
      })
    );
  });
  form.on("field", (name, value) => {
    // name:字段名
    // value:值
    console.log("数据:", name, value);
  });
  //接收文件数据
  form.on("file", (name, file) => {
    console.log("文件:", name, file);
  });
  //表单解析完成
  form.on("close", () => {
    console.log("完成");
  });
});
app.use("*", function (req, res, next) {
  // res.setHeader("token", req.headers["token"]);
  next();
});

app.use("/dev-api", dev);
app.listen(5000, function () {
  console.log("启动");
});
